<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 左侧背景 -->
      <div class="login-bg">
        <div class="bg-content">
          <h1 class="bg-title">欢迎来到在线教育平台</h1>
          <p class="bg-subtitle">开启您的学习之旅</p>
          <div class="bg-features">
            <div class="feature-item">
              <el-icon><VideoPlay /></el-icon>
              <span>海量优质课程</span>
            </div>
            <div class="feature-item">
              <el-icon><Trophy /></el-icon>
              <span>专业认证考试</span>
            </div>
            <div class="feature-item">
              <el-icon><User /></el-icon>
              <span>个性化学习</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧登录表单 -->
      <div class="login-form-wrapper">
        <div class="login-form">
          <div class="form-header">
            <h2 class="form-title">学生登录</h2>
            <p class="form-subtitle">请输入您的账号信息</p>
          </div>
          
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form-content"
            @keyup.enter="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名/手机号/邮箱"
                size="large"
                clearable
                :prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
                :prefix-icon="Lock"
              />
            </el-form-item>
            
            <el-form-item v-if="showCaptcha" prop="captcha">
              <div class="captcha-wrapper">
                <el-input
                  v-model="loginForm.captcha"
                  placeholder="请输入验证码"
                  size="large"
                  clearable
                  :prefix-icon="Key"
                  class="captcha-input"
                />
                <div class="captcha-image" @click="refreshCaptcha">
                  <img :src="captchaUrl" alt="验证码" />
                  <div class="captcha-refresh">
                    <el-icon><Refresh /></el-icon>
                  </div>
                </div>
              </div>
            </el-form-item>
            
            <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe">
                记住我
              </el-checkbox>
              <el-link type="primary" @click="handleForgotPassword">
                忘记密码？
              </el-link>
            </div>
            
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
            
            <div class="form-footer">
              <span>还没有账号？</span>
              <el-link type="primary" @click="handleRegister">
                立即注册
              </el-link>
            </div>
          </el-form>
          
          <!-- 第三方登录 -->
          <div class="third-party-login">
            <div class="divider">
              <span>其他登录方式</span>
            </div>
            <div class="third-party-buttons">
              <el-button
                circle
                size="large"
                class="third-party-btn wechat"
                @click="handleThirdPartyLogin('wechat')"
              >
                <el-icon><ChatDotRound /></el-icon>
              </el-button>
              <el-button
                circle
                size="large"
                class="third-party-btn qq"
                @click="handleThirdPartyLogin('qq')"
              >
                <el-icon><User /></el-icon>
              </el-button>
              <el-button
                circle
                size="large"
                class="third-party-btn phone"
                @click="handlePhoneLogin"
              >
                <el-icon><Iphone /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 手机登录对话框 -->
    <el-dialog
      v-model="phoneLoginVisible"
      title="手机号登录"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="phoneFormRef"
        :model="phoneForm"
        :rules="phoneRules"
        label-width="0"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="phoneForm.phone"
            placeholder="请输入手机号"
            size="large"
            clearable
            :prefix-icon="Iphone"
          />
        </el-form-item>
        
        <el-form-item prop="code">
          <div class="sms-wrapper">
            <el-input
              v-model="phoneForm.code"
              placeholder="请输入验证码"
              size="large"
              clearable
              :prefix-icon="Key"
              class="sms-input"
            />
            <el-button
              size="large"
              :disabled="smsCountdown > 0"
              @click="sendSmsCode"
            >
              {{ smsCountdown > 0 ? `${smsCountdown}s` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="phoneLoginVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="phoneLoading"
          @click="handlePhoneLoginSubmit"
        >
          登录
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Lock,
  Key,
  Refresh,
  VideoPlay,
  Trophy,
  ChatDotRound,
  Iphone
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { getCaptcha, sendSmsCode as apiSendSmsCode } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()
const phoneFormRef = ref()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  rememberMe: false
})

// 手机登录表单数据
const phoneForm = reactive({
  phone: '',
  code: ''
})

// 状态数据
const loading = ref(false)
const phoneLoading = ref(false)
const phoneLoginVisible = ref(false)
const showCaptcha = ref(false)
const captchaUrl = ref('')
const smsCountdown = ref(0)
let smsTimer = null

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '用户名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 位', trigger: 'blur' }
  ]
}

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为 6 位', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    const loginData = {
      username: loginForm.username,
      password: loginForm.password,
      rememberMe: loginForm.rememberMe
    }
    
    if (showCaptcha.value) {
      loginData.captcha = loginForm.captcha
    }
    
    await userStore.login(loginData)
    
    ElMessage.success('登录成功')
    
    // 跳转到首页或之前访问的页面
    const redirect = router.currentRoute.value.query.redirect || '/'
    router.push(redirect)
    
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '登录失败，请重试')
    
    // 登录失败后显示验证码
    if (!showCaptcha.value) {
      showCaptcha.value = true
      await refreshCaptcha()
    } else {
      await refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const response = await getCaptcha()
    captchaUrl.value = response.data.captchaUrl
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 忘记密码
const handleForgotPassword = () => {
  router.push('/auth/forgot-password')
}

// 注册
const handleRegister = () => {
  router.push('/auth/register')
}

// 第三方登录
const handleThirdPartyLogin = (type) => {
  ElMessage.info(`${type} 登录功能开发中...`)
}

// 手机登录
const handlePhoneLogin = () => {
  phoneLoginVisible.value = true
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!phoneForm.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(phoneForm.phone)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  
  try {
    await apiSendSmsCode({ phone: phoneForm.phone, type: 'login' })
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    smsCountdown.value = 60
    smsTimer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(smsTimer)
        smsTimer = null
      }
    }, 1000)
    
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.message || '发送验证码失败')
  }
}

// 手机登录提交
const handlePhoneLoginSubmit = async () => {
  if (!phoneFormRef.value) return
  
  try {
    const valid = await phoneFormRef.value.validate()
    if (!valid) return
    
    phoneLoading.value = true
    
    await userStore.phoneLogin({
      phone: phoneForm.phone,
      code: phoneForm.code
    })
    
    ElMessage.success('登录成功')
    phoneLoginVisible.value = false
    
    // 跳转到首页或之前访问的页面
    const redirect = router.currentRoute.value.query.redirect || '/'
    router.push(redirect)
    
  } catch (error) {
    console.error('手机登录失败:', error)
    ElMessage.error(error.message || '登录失败，请重试')
  } finally {
    phoneLoading.value = false
  }
}

// 组件挂载
onMounted(() => {
  // 如果已经登录，直接跳转
  if (userStore.isLoggedIn) {
    const redirect = router.currentRoute.value.query.redirect || '/'
    router.push(redirect)
  }
})

// 组件卸载
onUnmounted(() => {
  if (smsTimer) {
    clearInterval(smsTimer)
    smsTimer = null
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-lg);
}

.login-wrapper {
  width: 100%;
  max-width: 1000px;
  background: var(--bg-color);
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  min-height: 600px;
}

.login-bg {
  flex: 1;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light-2) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xxxl);
  color: white;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
    opacity: 0.3;
  }
}

.bg-content {
  text-align: center;
  position: relative;
  z-index: 1;
}

.bg-title {
  font-size: 2.5rem;
  font-weight: 600;
  margin-bottom: var(--spacing-lg);
  line-height: 1.2;
}

.bg-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin-bottom: var(--spacing-xxxl);
}

.bg-features {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.feature-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  font-size: 1.1rem;
  
  .el-icon {
    font-size: 1.5rem;
  }
}

.login-form-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xxxl);
}

.login-form {
  width: 100%;
  max-width: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: var(--spacing-xxxl);
}

.form-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: var(--text-color-primary);
  margin-bottom: var(--spacing-sm);
}

.form-subtitle {
  color: var(--text-color-secondary);
  font-size: var(--font-size-base);
}

.login-form-content {
  .el-form-item {
    margin-bottom: var(--spacing-lg);
  }
  
  .el-input {
    --el-input-height: 48px;
  }
}

.captcha-wrapper {
  display: flex;
  gap: var(--spacing-md);
  
  .captcha-input {
    flex: 1;
  }
  
  .captcha-image {
    width: 120px;
    height: 48px;
    border: 1px solid var(--border-color-base);
    border-radius: var(--border-radius-base);
    cursor: pointer;
    position: relative;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .captcha-refresh {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;
      color: white;
    }
    
    &:hover .captcha-refresh {
      opacity: 1;
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: var(--font-size-medium);
  font-weight: 500;
  margin-bottom: var(--spacing-xl);
}

.form-footer {
  text-align: center;
  color: var(--text-color-secondary);
  
  .el-link {
    margin-left: var(--spacing-xs);
  }
}

.third-party-login {
  margin-top: var(--spacing-xxxl);
}

.divider {
  position: relative;
  text-align: center;
  margin-bottom: var(--spacing-xl);
  
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: var(--border-color-lighter);
  }
  
  span {
    background: var(--bg-color);
    padding: 0 var(--spacing-md);
    color: var(--text-color-secondary);
    font-size: var(--font-size-small);
  }
}

.third-party-buttons {
  display: flex;
  justify-content: center;
  gap: var(--spacing-lg);
}

.third-party-btn {
  width: 48px;
  height: 48px;
  
  &.wechat {
    color: #07c160;
    border-color: #07c160;
    
    &:hover {
      background: #07c160;
      color: white;
    }
  }
  
  &.qq {
    color: #12b7f5;
    border-color: #12b7f5;
    
    &:hover {
      background: #12b7f5;
      color: white;
    }
  }
  
  &.phone {
    color: var(--warning-color);
    border-color: var(--warning-color);
    
    &:hover {
      background: var(--warning-color);
      color: white;
    }
  }
}

.sms-wrapper {
  display: flex;
  gap: var(--spacing-md);
  
  .sms-input {
    flex: 1;
  }
}

// 响应式设计
@include respond-below(md) {
  .login-wrapper {
    flex-direction: column;
    max-width: 500px;
  }
  
  .login-bg {
    min-height: 200px;
    padding: var(--spacing-xl);
  }
  
  .bg-title {
    font-size: 2rem;
  }
  
  .bg-features {
    flex-direction: row;
    justify-content: center;
    gap: var(--spacing-xl);
  }
  
  .feature-item {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-xs);
    font-size: 0.9rem;
  }
  
  .login-form-wrapper {
    padding: var(--spacing-xl);
  }
}

@include respond-below(sm) {
  .login-container {
    padding: var(--spacing-md);
  }
  
  .bg-features {
    flex-direction: column;
    gap: var(--spacing-md);
  }
  
  .feature-item {
    flex-direction: row;
    justify-content: flex-start;
  }
  
  .login-form-wrapper {
    padding: var(--spacing-lg);
  }
  
  .third-party-buttons {
    gap: var(--spacing-md);
  }
  
  .third-party-btn {
    width: 40px;
    height: 40px;
  }
}
</style>